<?php

namespace Common;

use Common\Database\MysqliAdapter;
use Common\ORM\Model\User;
use Common\Database\Proxy;

class Factory
{

    protected static $proxy = null;

    /**
     * 创建database实例
     * @return Database
     */
    public static function createDatabase(): Database
    {
        $db = Database::getInstance();
        Register::set('db1', $db);
        return $db;
    }

    /**
     * 创建Mysqli实例
     * @return Proxy|MysqliAdapter
     */
    public static function getDatabase($id = 'proxy')
    {
        if ($id == 'proxy') {
            if (!self::$proxy) {
                self::$proxy = new Proxy();
            }
            return self::$proxy;
        }
        $key = 'database_' . $id;
        if ($id == 'slave') {
            //简单的随机分配slave库，需要根据业务和服务器配置等实际情况来定
            $slaves = Application::getInstance()->config['database']['slave'];
            $db_conf = $slaves[array_rand($slaves)];
        } else {
            $db_conf = Application::getInstance()->config['database'][$id];
        }
        $db = Register::get($key);
        if (!$db) {
            $db = new MysqliAdapter();
            $db->connect($db_conf['host'], $db_conf['user'], $db_conf['password'], $db_conf['dbname']);
            Register::set($key, $db);
        }
        return $db;
    }

    /**
     * 创建User模型案例说明，实际框架中需要用getModel
     * @param $id
     * @return User
     */
    public static function createUser($id): User
    {
        //使用注册器模式来工厂模式生成类
        $key = 'User_' . $id;
        $user = Register::get($key);
        if (!$user) {
            $user = new User($id);
            Register::set($key, $user);
        }
        return $user;
    }

    /**
     * 通用获取模型
     * @param $name
     * @return bool
     */
    static function getModel($name)
    {
        $key = 'app_model_' . $name;
        $model = Register::get($key);
        if (!$model) {
            $class = '\\App\\Model\\' . ucwords($name);
            $model = new $class;
            Register::set($key, $model);
        }
        return $model;
    }
}